package api

import (
	"net/http"

	"example.com/example/dao"
	"example.com/example/model"

	"github.com/gin-gonic/gin"
	"github.com/guregu/null"
	"github.com/julienschmidt/httprouter"
)

var (
	_ = null.Bool{}
)

func configEnvironmentRouter(router *httprouter.Router) {
	router.GET("/environment", GetAllEnvironment)
	router.POST("/environment", AddEnvironment)
	router.GET("/environment/:argId", GetEnvironment)
	router.PUT("/environment/:argId", UpdateEnvironment)
	router.DELETE("/environment/:argId", DeleteEnvironment)
}

func configGinEnvironmentRouter(router gin.IRoutes) {
	router.GET("/environment", ConverHttprouterToGin(GetAllEnvironment))
	router.POST("/environment", ConverHttprouterToGin(AddEnvironment))
	router.GET("/environment/:argId", ConverHttprouterToGin(GetEnvironment))
	router.PUT("/environment/:argId", ConverHttprouterToGin(UpdateEnvironment))
	router.DELETE("/environment/:argId", ConverHttprouterToGin(DeleteEnvironment))
}

// GetAllEnvironment is a function to get a slice of record(s) from environment table in the custom_process database
// @Summary Get list of Environment
// @Tags Environment
// @Description GetAllEnvironment is a handler to get a slice of record(s) from environment table in the custom_process database
// @Accept  json
// @Produce  json
// @Param   page     query    int     false        "page requested (defaults to 0)"
// @Param   pagesize query    int     false        "number of records in a page  (defaults to 20)"
// @Param   order    query    string  false        "db sort order column"
// @Success 200 {object} api.PagedResults{data=[]model.Environment}
// @Failure 400 {object} api.HTTPError
// @Failure 404 {object} api.HTTPError
// @Router /environment [get]
// http "http://localhost:8080/environment?page=0&pagesize=20" X-Api-User:user123
func GetAllEnvironment(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	ctx := initializeContext(r)
	page, err := readInt(r, "page", 0)
	if err != nil || page < 0 {
		returnError(ctx, w, r, dao.ErrBadParams)
		return
	}

	pagesize, err := readInt(r, "pagesize", 20)
	if err != nil || pagesize <= 0 {
		returnError(ctx, w, r, dao.ErrBadParams)
		return
	}

	order := r.FormValue("order")

	if err := ValidateRequest(ctx, r, "environment", model.RetrieveMany); err != nil {
		returnError(ctx, w, r, err)
		return
	}

	records, totalRows, err := dao.GetAllEnvironment(ctx, page, pagesize, order)
	if err != nil {
		returnError(ctx, w, r, err)
		return
	}

	result := &PagedResults{Page: page, PageSize: pagesize, Data: records, TotalRecords: totalRows}
	writeJSON(ctx, w, result)
}

// GetEnvironment is a function to get a single record from the environment table in the custom_process database
// @Summary Get record from table Environment by  argId
// @Tags Environment
// @ID argId
// @Description GetEnvironment is a function to get a single record from the environment table in the custom_process database
// @Accept  json
// @Produce  json
// @Param  argId path int64 true "id"
// @Success 200 {object} model.Environment
// @Failure 400 {object} api.HTTPError
// @Failure 404 {object} api.HTTPError "ErrNotFound, db record for id not found - returns NotFound HTTP 404 not found error"
// @Router /environment/{argId} [get]
// http "http://localhost:8080/environment/1" X-Api-User:user123
func GetEnvironment(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	ctx := initializeContext(r)

	argId, err := parseUint64(ps, "argId")
	if err != nil {
		returnError(ctx, w, r, err)
		return
	}

	if err := ValidateRequest(ctx, r, "environment", model.RetrieveOne); err != nil {
		returnError(ctx, w, r, err)
		return
	}

	record, err := dao.GetEnvironment(ctx, argId)
	if err != nil {
		returnError(ctx, w, r, err)
		return
	}

	writeJSON(ctx, w, record)
}

// AddEnvironment add to add a single record to environment table in the custom_process database
// @Summary Add an record to environment table
// @Description add to add a single record to environment table in the custom_process database
// @Tags Environment
// @Accept  json
// @Produce  json
// @Param Environment body model.Environment true "Add Environment"
// @Success 200 {object} model.Environment
// @Failure 400 {object} api.HTTPError
// @Failure 404 {object} api.HTTPError
// @Router /environment [post]
// echo '{"id": 63,"name": "ayoISQwbUDAGWThLDNxJpODUm","create_time": "2220-11-26T01:18:20.689226893+08:00","update_time": "2020-12-23T11:51:10.676440714+08:00"}' | http POST "http://localhost:8080/environment" X-Api-User:user123
func AddEnvironment(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	ctx := initializeContext(r)
	environment := &model.Environment{}

	if err := readJSON(r, environment); err != nil {
		returnError(ctx, w, r, dao.ErrBadParams)
		return
	}

	if err := environment.BeforeSave(); err != nil {
		returnError(ctx, w, r, dao.ErrBadParams)
	}

	environment.Prepare()

	if err := environment.Validate(model.Create); err != nil {
		returnError(ctx, w, r, dao.ErrBadParams)
		return
	}

	if err := ValidateRequest(ctx, r, "environment", model.Create); err != nil {
		returnError(ctx, w, r, err)
		return
	}

	var err error
	environment, _, err = dao.AddEnvironment(ctx, environment)
	if err != nil {
		returnError(ctx, w, r, err)
		return
	}

	writeJSON(ctx, w, environment)
}

// UpdateEnvironment Update a single record from environment table in the custom_process database
// @Summary Update an record in table environment
// @Description Update a single record from environment table in the custom_process database
// @Tags Environment
// @Accept  json
// @Produce  json
// @Param  argId path int64 true "id"
// @Param  Environment body model.Environment true "Update Environment record"
// @Success 200 {object} model.Environment
// @Failure 400 {object} api.HTTPError
// @Failure 404 {object} api.HTTPError
// @Router /environment/{argId} [put]
// echo '{"id": 63,"name": "ayoISQwbUDAGWThLDNxJpODUm","create_time": "2220-11-26T01:18:20.689226893+08:00","update_time": "2020-12-23T11:51:10.676440714+08:00"}' | http PUT "http://localhost:8080/environment/1"  X-Api-User:user123
func UpdateEnvironment(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	ctx := initializeContext(r)

	argId, err := parseUint64(ps, "argId")
	if err != nil {
		returnError(ctx, w, r, err)
		return
	}

	environment := &model.Environment{}
	if err := readJSON(r, environment); err != nil {
		returnError(ctx, w, r, dao.ErrBadParams)
		return
	}

	if err := environment.BeforeSave(); err != nil {
		returnError(ctx, w, r, dao.ErrBadParams)
	}

	environment.Prepare()

	if err := environment.Validate(model.Update); err != nil {
		returnError(ctx, w, r, dao.ErrBadParams)
		return
	}

	if err := ValidateRequest(ctx, r, "environment", model.Update); err != nil {
		returnError(ctx, w, r, err)
		return
	}

	environment, _, err = dao.UpdateEnvironment(ctx,
		argId,
		environment)
	if err != nil {
		returnError(ctx, w, r, err)
		return
	}

	writeJSON(ctx, w, environment)
}

// DeleteEnvironment Delete a single record from environment table in the custom_process database
// @Summary Delete a record from environment
// @Description Delete a single record from environment table in the custom_process database
// @Tags Environment
// @Accept  json
// @Produce  json
// @Param  argId path int64 true "id"
// @Success 204 {object} model.Environment
// @Failure 400 {object} api.HTTPError
// @Failure 500 {object} api.HTTPError
// @Router /environment/{argId} [delete]
// http DELETE "http://localhost:8080/environment/1" X-Api-User:user123
func DeleteEnvironment(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	ctx := initializeContext(r)

	argId, err := parseUint64(ps, "argId")
	if err != nil {
		returnError(ctx, w, r, err)
		return
	}

	if err := ValidateRequest(ctx, r, "environment", model.Delete); err != nil {
		returnError(ctx, w, r, err)
		return
	}

	rowsAffected, err := dao.DeleteEnvironment(ctx, argId)
	if err != nil {
		returnError(ctx, w, r, err)
		return
	}

	writeRowsAffected(w, rowsAffected)
}
